package com.ifd.iview.common;

import java.sql.Connection;
import java.sql.DriverManager;

import org.apache.log4j.Logger;

import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400JDBCDriver;

public class ServiceLocatorLRU {

	public static final int AS400_SERVICE_FILE = AS400.FILE;
	public static final int AS400_SERVICE_PRINT = AS400.PRINT;
	public static final int AS400_SERVICE_COMMAND = AS400.COMMAND;
	public static final int AS400_SERVICE_DATAQUEUE = AS400.DATAQUEUE;
	public static final int AS400_SERVICE_DATABASE = AS400.DATABASE;
	public static final int AS400_SERVICE_RECORDACCESS = AS400.RECORDACCESS;
	public static final int AS400_SERVICE_CENTRAL = AS400.CENTRAL;
	public static final int AS400_SERVICE_SIGNON = AS400.SIGNON;
	
	private static Logger logger = Logger.getLogger(ServiceLocatorLRU.class);
	
	public static AS400 getAS400Connection(int service){
		String host = IviewAppConfig.getInstance().getProperty("server.host");
		String user = IviewAppConfig.getInstance().getProperty("server.username");
		String pass = IviewAppConfig.getInstance().getProperty("server.password");
		AS400 as400 = new AS400(host,user,pass);
		try {
			as400.connectService(service);
			as400.setGuiAvailable(false);
			return as400;
		} catch (Exception e) {
			logger.error("Unable to get AS400 connection", e);
			return null;
		}
	}
	
	public static void returnAS400Connection(AS400 as400){
		as400.disconnectAllServices();
	}
	
	public static Connection getJDBCConnection(){
		Connection conn = null;
		try {
			DriverManager.registerDriver (new AS400JDBCDriver());
			String host = IviewAppConfig.getInstance().getProperty("server.host");
			String user = IviewAppConfig.getInstance().getProperty("server.username");
			String pass = IviewAppConfig.getInstance().getProperty("server.password");
			String dbnm = IviewAppConfig.getInstance().getProperty("server.database");
			String conStr = "jdbc:as400://" + host.trim() + ";libraries=" + 
							dbnm.trim() + ";naming=sql;errors=full";
			conn = DriverManager.getConnection(conStr,user,pass);
		} catch (Exception e) {
			logger.error("Unable to get AS400 JDBC connection", e);
		}
		return conn;
	}
	
	public static void returnJDBCConnection(Connection conn){
		try {
			conn.close();
		} catch (Exception e) {
		}
	}
}
